﻿using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.AvalonEdit.Editing;
using Oxage.Drivers;
using Oxage.Models;

namespace Oxage.Services
{
	public class DebugService
	{
		public static IProjectDebugger CurrentProjectDebugger
		{
			get
			{
				return currentProjectDebugger;
			}
			set
			{
				if (currentProjectDebugger != value)
				{
					var oldValue = currentProjectDebugger;
					currentProjectDebugger = value;
					OnCurrentProjectDebuggerChanged(oldValue, value);
				}
			}
		}
		private static IProjectDebugger currentProjectDebugger;

		public static event EventHandler<NewValueEventArgs<IProjectDebugger>> CurrentProjectDebuggerChanged;
		protected static void OnCurrentProjectDebuggerChanged(IProjectDebugger oldValue, IProjectDebugger newValue)
		{
			if (CurrentProjectDebuggerChanged != null)
			{
				CurrentProjectDebuggerChanged(null, new NewValueEventArgs<IProjectDebugger>(oldValue, newValue));
			}
		}

		public static IConnector CurrentMachineController
		{
			get
			{
				//return App.ViewModel.MachineController;
				return controller;
			}
			set
			{
				controller = value;
			}
		}

		private static IConnector controller = new VirtualConnector();

		public static void ShowCurrentLineBookmark(int lineNumber)
		{
			var editor = TextEditorService.Editor;
			if (editor != null)
			{
				editor.CurrentLineBookmark = lineNumber;
			}
		}

		public static void HideCurrentLineBookmark()
		{
			var editor = TextEditorService.Editor;
			if (editor != null)
			{
				editor.CurrentLineBookmark = 0;
			}
		}

		public static IEnumerable<IBookmark> GetBreakpoints()
		{
			var editor = TextEditorService.Editor;
			if (editor == null)
			{
				return new List<BreakpointBookmark>().OfType<IBookmark>();
			}

			return editor.BookmarkColumn.Bookmarks.Where(x => x is BreakpointBookmark);
		}

		//NOTE: This is only for G code?
		//public static IEnumerable<ICodeLine> GetCodeLines()
		//{
		//  TextEditorService.GetLines(); //yield return text, line number, anchors, etc.
		//}

		public static void ToggleBreakpointAtCaret()
		{
			if (TextEditorService.Editor != null)
			{
				TextEditorService.Editor.ToggleBreakpoint(TextEditorService.Editor.GetCaretLineNumber());
			}
		}

		public static void DeleteAllBreakpoints()
		{
			if (TextEditorService.Editor != null)
			{
				TextEditorService.Editor.DeleteAllBreakpoints();
			}
		}

		public static int GetBreakpointsCount()
		{
			if (TextEditorService.Editor != null)
			{
				return TextEditorService.Editor.BookmarkColumn.Bookmarks.Count(x => x is BreakpointBookmark);
			}
			return 0;
		}
	}
}
